import logging
import random

from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework.generics import CreateAPIView, UpdateAPIView, RetrieveAPIView, GenericAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from answers.models import QuesUserModel, LabelUserModel, CommentModel, QuesModel
from celery_tasks.sms.utils.tasks import send_sms_code
from mlh.utils import constants
from mlh.utils.pagination import StandardResultsSetPagination
from tucao.models import Collections
from users.models import Exp, Dynamics
from users.serializers import SMSCodeSerializers, ExpcationSerializer, DynamicsSerializer, UserQuestionsSerializer, \
    UserLabelsSerializer, UserTucaosSerializer, UserAnswersSerializer, MyQuestionsSerializer

logger = logging.getLogger('mlh')
from users.models import UserDetail, Company, School, User
from users.serializers import RegisterSerializers, AccountSettingSerializers, UserDetailSerializers, \
    UserCenterSerializers, CompanySettingSerializers, SchoolSettingSerializers, UserEditDetailSerializers, \
    UserEditSettingSerializers


class RegisterView(CreateAPIView):
    serializer_class = RegisterSerializers

    def get_object(self):
        print(self.request.data)

        return self.request.user


class SMSCodeView(GenericAPIView):
    '''短信验证码'''
    serializer_class = SMSCodeSerializers

    def get(self, request, mobile):
        # 接收并校验参数 由序列化器完成
        s = self.get_serializer(data=request.query_params)
        # get_serializer
        s.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 保存短信验证码  发送记录
        redis_conn = get_redis_connection('verify_codes')

        # redis 管道 (两个setex进行两次网络通讯提取redis数据库，效率低)
        pl = redis_conn.pipeline()  # 管道将所有命令收集但不执行，知道execute()命令
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 让管道通知redis执行命令
        pl.execute()

        # 使用celery发送短信验证码
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        temp_id = constants.SMS_CODE_TEMP_ID
        send_sms_code.delay(mobile, sms_code, expires, temp_id)

        return Response({'message': 'ok'})


# 展示用户信息
class UserCenterInfo(RetrieveAPIView):
    serializer_class = UserCenterSerializers
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 展示工作经历

class UserExpView(ListAPIView):
    serializer_class = ExpcationSerializer

    # filter_backends = (OrderingFilter,)
    # ordering_fields = ('id')
    # queryset = Exp.objects.all(user=self.request.user)
    # def get_object(self):
    #     return Exp.objects.all(user=self.request.user)
    def get_queryset(self):
        return Exp.objects.filter(user=self.request.user).order_by("id")


# 更新user表用户信息
class AccountSettings(UpdateAPIView):
    permission_classes = [IsAuthenticated]  # 指明必须登录认证后才能访问
    queryset = User.objects.all()
    serializer_class = AccountSettingSerializers
    lookup_url_kwarg = "user_id"
    # def get_object(self ,*args, **kwargs ):
    #     return self.request.user


# 更新userdetail表用户信息
class AccountDtailSettings(UpdateAPIView):
    permission_classes = [IsAuthenticated]  # 指明必须登录认证后才能访问
    serializer_class = UserDetailSerializers
    queryset = UserDetail.objects.all()
    lookup_field = "user_id"
    lookup_url_kwarg = "user_id"
    # def get_object(self ,*args, **kwargs ):
    #     print(self.request.data)
    #     ret = UserDetail.objects.filter(user=self.request.user).first()
    #     # print(ret)
    #     return ret


class CompanySettings(UpdateAPIView):
    permission_classes = [IsAuthenticated]  # 指明必须登录认证后才能访问
    serializer_class = CompanySettingSerializers
    queryset = Company.objects.all()
    lookup_field = "user_id"
    lookup_url_kwarg = "user_id"
    # def get_object(self, *args, **kwargs):
    #     return Company.objects.filter(user=self.request.user).first()


class SchoolSettings(UpdateAPIView):
    permission_classes = [IsAuthenticated]  # 指明必须登录认证后才能访问
    serializer_class = SchoolSettingSerializers

    def get_object(self, *args, **kwargs):
        return School.objects.filter(user=self.request.user).first()


class UserEditSettins(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    queryset = UserDetail.objects.all()
    lookup_url_kwarg = 'user_id'
    lookup_field = 'user_id'

    def update(self, request, *args, **kwargs):
        print(self.request.data)
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        user_instance = instance.user

        # 序列化校验
        serializer_user = UserEditSettingSerializers(user_instance, data=self.request.data, partial=partial)
        serializer_detail = UserEditDetailSerializers(instance, data=self.request.data, partial=partial)
        serializer_user.is_valid(raise_exception=True)
        serializer_detail.is_valid(raise_exception=True)
        self.perform_update(serializer_user)
        self.perform_update(serializer_detail)
        print(serializer_detail.data, serializer_user.data)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer_user.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)


class EducationViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    serializer_class = ExpcationSerializer
    permission_classes = [IsAuthenticated]
    lookup_url_kwarg = 'id'
    lookup_field = 'id'

    # lookup_url_kwarg = "pk"
    def get_queryset(self):
        return self.request.user.exp

    # def list(self,request,*args,**kwargs):
    #     queryset=self.get_queryset()
    #     serializer=self.get_serializer(queryset,many=True)
    #     user=self.request.user
    #     return Response({
    #         'user_id': user.id,
    #         'education': serializer.data,
    #     })
    # 新增教育经历
    def create(self, request, *args, **kwargs):
        print("ok")
        user = self.request.user
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        exp=Exp.objects.create(user=user,**request.data)
        # install  = table.ob.get(id=self.kwargs['user_id']).first()
        all_exp=Exp.objects.filter(user=user)
        exp_serializer=ExpcationSerializer(all_exp,many=True)
        return Response(exp_serializer.data)

    # 更新教育经历
    def update(self, request, *args, **kwargs):
        print("ok")
        exp = self.get_object()
        partial = kwargs.pop('partial', False)

        serializer = ExpcationSerializer(instance=exp, data=request.data, partial=partial)
        serializer.is_valid()
        serializer.save()

        all_exp = Exp.objects.filter(user=self.request.user).order_by("id")
        exp_serializer = ExpcationSerializer(all_exp, many=True)
        return Response(exp_serializer.data)


# url(r'^user/dynamics/$',views.DynamicsListView.as_view())
class DynamicsListView(ListAPIView):
    serializer_class = DynamicsSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = Dynamics.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


# url(r'^user/attentions/questions/$',views.UserAttentionsQuestionsView.as_view())
class UserAttentionsQuestionsView(ListAPIView):
    serializer_class = UserQuestionsSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = QuesUserModel.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


# url(r'^user/attentions/labels/$',views.UserAttentionsLabelsView.as_view())
class UserAttentionsLabelsView(ListAPIView):
    serializer_class = UserLabelsSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = LabelUserModel.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


# url(r'^user/collections/tucaos/$',views.UserCollectTucaosView.as_view())
class UserCollectTucaosView(ListAPIView):
    serializer_class = UserTucaosSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = Collections.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


# url(r'^user/answers/$',views.UserAnswersView.as_view())
class UserAnswersView(ListAPIView):
    serializer_class = UserAnswersSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = CommentModel.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


# url(r'^user/questions/$',views.UserQuestionsView.as_view())
class UserQuestionsView(ListAPIView):
    serializer_class = MyQuestionsSerializer
    # 分页
    pagination_class = StandardResultsSetPagination

    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = QuesModel.objects.filter(user=self.request.user)
        if queryset:
            queryset = queryset.order_by('-create_time')
        return queryset


class IntruduceCompleteView(RetrieveAPIView):
    serializer_class = UserEditSettingSerializers
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        total_count=0
        data_dict=dict(serializer.data)
        print
        if data_dict.get('exp',None):
            for num in data_dict.get('exp',None):
                total_count+=num
        if  data_dict.get('school',None):
            total_count+=data_dict['school']
        if data_dict.get('company', None):
            total_count+=data_dict['company']
        if data_dict.get('company', None):
            total_count+=data_dict['detail']
        total_amount=constants.DATABASE_TOTAL_AMOUNT
        ret=total_count/total_amount
        sophistication="%.0f%%"%(ret*100)
        data_dict['sophistication']=sophistication
        UserDetail.objects.filter(user=request.user).update(sophistication=sophistication)
        print(data_dict)
        return Response(data_dict)


class AvatarView(APIView):
    # permission_classes = [IsAuthenticated]
    def patch(self,request:Request):

        avatar_url=request.data['avatar_url']
        User.objects.update(id=request.user.id,avatar_url=avatar_url)
        return Response({"massage":"ok"})